package com.dy.分类.链表.合并两个有序链表;

class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}

/*
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例：

输入：1->2->4, 1->3->4
输出：1->1->2->3->4->4
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode head = new ListNode(0);
        ListNode p = head, a1 = l1, a2 = l2;
        while (a1 != null && a2 != null) {
            if (a1.val <= a2.val) {
                p.next = a1;
                a1 = a1.next;
            } else {
                p.next = a2;
                a2 = a2.next;
            }

            p = p.next;
            p.next = null;


        }
        if (a1 != null) {
            p.next = a1;
        }
        if (a2 != null) {
            p.next = a2;
        }

        return head.next;
    }


    //递归
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        if(l1==null) return l2;
        if(l2==null) return l1;
        ListNode res;
        if(l1.val<=l2.val){
            res = l1;
            res.next = mergeTwoLists2(l1.next,l2);
        }
        else{
            res = l2;
            res.next = mergeTwoLists2(l1,l2.next);
        }
        return res;
    }

}